﻿; (function ($) {
    var util={};

    util.deviceType=function(){
        var sUserAgent= navigator.userAgent.toLowerCase();

        var bIsIpad= sUserAgent.match(/ipad/i) == "ipad";

        var bIsIphoneOs= sUserAgent.match(/iphone os/i) == "iphone os";

        var bIsMidp= sUserAgent.match(/midp/i) == "midp";

        var bIsUc7= sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";

        var bIsUc= sUserAgent.match(/ucweb/i) == "ucweb";

        var bIsAndroid= sUserAgent.match(/android/i) == "android";

        var bIsCE= sUserAgent.match(/windows ce/i) == "windows ce";

        var bIsWM= sUserAgent.match(/windows mobile/i) == "windows mobile";

        if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {

            return 'mobile';

        } else {

            return 'pc';
        }

    };
    util.eventType=util.deviceType()=="mobile"?"tap":"click";

    util.stopBubble=function (e) {
        if (e && e.stopPropagation) {
            //因此它支持W3C的stopPropagation()方法 
            e.stopPropagation();
        } else {
            //否则，我们需要使用IE的方式来取消事件冒泡 
            window.event.cancelBubble = true;
        }
    };

    util.obj2list = function(obj){
        var list = [];
        for(var i in obj){
            list.push(obj[i]);
        }
        return list;
    };

    util.list2obj = function(list,key){
        var obj = {};
        for(var i=0;i<list.length;i++){
            var idata = list[i];
            obj[idata[key]] = idata;
        }
        return obj;
    };
    util.getUrlParam = function(key){
		var urlstr = window.location.href.split("?"),
            params = {};
        if (urlstr[1]) {
			
				var items = urlstr[1].split("&");
				
				for (i = 0; i < items.length; i++) {
				
					itemarr = items[i].split("=");
					
					params[itemarr[0]] = itemarr[1];
				}
			}
        return key?params[key]:params;
        
    }
    util.toUrlWithParam=function(toUrl,param){
		
		var value = "",itemarr = [],params;


		params = this.getUrlParam();
		
		if(param){
			
			var temps = param.split("&"),tempparam;
		
			for(var i=0;i<temps.length;i++){
				
				tempparam = temps[i].split('=');
				
				params[tempparam[0]] = tempparam[1];
			}
		}
		
		
		var paramslist = [];
		
		for(var key in params){
			
			paramslist.push(key + '=' + params[key]);
		}
		location.href= toUrl + "?" + paramslist.join("&");
	}
    //构建ajax
    util.buildAjaxParams=function(param){
			var _param = {
				type: "post",
				dataType: "json",
				url: "",
				data: null,
				beforeSend: function () {
					
				},
				success: null,
				error: function (XMLHttpRequest, textStatus, errorThrown){
					
				}
			};
			
			$.extend(_param,param);
			
			//var baseInfo = this.getBaseAjaxParam();
			
			var action = param.data.action,
				interfaceType = param.interfaceType||'Product',
				_req = {
					'Locale':null,
					'CustomerID':(param.customerId?param.customerId:null),
					'UserID':(param.userId?param.userId:null),
					'OpenID':null,
					'Token':null,
					'Parameters':param.data,
                    'random':Math.random()
				};

			delete param.data.action;

			var _data = {
				'req':JSON.stringify(_req)
			};
			
			_param.data = _data;

			_param.url = _param.url+'?type='+interfaceType+'&action='+action;

			return _param;
	};
    //最新的ajax封装
	util.ajax=function(param){

			var _param;

			if(param.url.indexOf('Gateway.ashx')!=-1){

				_param = util.buildAjaxParams(param);
			}else{

				_param = util.buildAjaxParams(param);
			}
			//_param.url =  _param.url;
			
			$.ajax(_param);
	};

    //组织默认事件
    util.stopBubble=function (e) {
        if (e && e.stopPropagation) {
            //因此它支持W3C的stopPropagation()方法 
            e.stopPropagation();
        }
        else {
            //否则，我们需要使用IE的方式来取消事件冒泡 
            window.event.cancelBubble = true;
        }
        e.preventDefault();
    };
    util.reachBottom=function(vars) {
        var scrollTop = 0;
        var clientHeight = 0;
        var scrollHeight = 0;
        if (document.documentElement && document.documentElement.scrollTop) {
            scrollTop = document.documentElement.scrollTop;
        } else if (document.body) {
            scrollTop = document.body.scrollTop;
        }
        if (document.body.clientHeight && document.documentElement.clientHeight) {
            clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight: document.documentElement.clientHeight;
        } else {
            clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight: document.documentElement.clientHeight;
        }
        scrollHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
        if (scrollTop + clientHeight>= scrollHeight-vars) {
            return true;
        } else {
            return false;
        }
    };
    $.util=util;



    /******************************    UI组件    ******************************/

    var UI = {
        //临时代码
        startLoad:function(pics,callback,txt){
            var index = 0;
            var len = pics.length;
            var img = new Image();
            var note = txt||"页面正在加载，建议WIFI环境下观看";
            var loadHtml = '<div class="loadPage" style="z-index: 999;width: 100%;position: absolute; top: 0;bottom: 0;background: #ffffff;">\
                                <div style="position: absolute; left: 50%; top: 130px; margin-left: -40px; z-index: 999; width: 81px; height: 72px; text-align: center;">\
                                    <em class="loadNum" style="display: inline-block;font-style: normal; color: #333; margin: 30px auto;">0%</em>\
                                </div>\
                                <section style="position: absolute;left: 50%; top: 260px;margin-left: -200px; width: 400px;">\
                                <div class="loading" style="position: relative;width:100%;height: 10px; background:#ccc;border-radius: 10px;overflow: hidden;"><div class="inner" style="position: absolute; left: 0;width: 0%;height: 10px;background:#333;"></div></div>\
                                </section>\
                                <p class="loadInfo" style="position: absolute; left: 50%; top: 285px; color: #a3ca99; line-height: 50px; font-weight:bold;text-align: center; width: 200px; margin-left: -100px;">'+note+'</p>\
                            </div>';
            var $loadHtml=$(loadHtml);
            if($('.loadPage').length){
                $('.loadPage').remove();
            }else{
                $loadHtml.prependTo("body");
            }
            var progress = function(w){
                console.log(w);
                $('.loading .inner').animate({width:w}, 100, 'linear', function(){$('.loadNum').html(w)});
            }
            var load = function(){
                img.src = pics[index];
                img.onload = function() {
                    console.log(index);
//                    console.log(new Date().getTime())
                    index ++ ;
                    progress(Math.floor((index / len) * 100) + "%");
                    if (index < len) {
                        load();
                    }else{
                        setTimeout(function(){
                            $loadHtml.hide();
                            if(callback){
                                callback();
                            }

                        },500);

                    }
                }
                img.onerror=function(){
                    setTimeout(function(){
                        index++
                        load();
                    },500);
                }
                return img;
            }
            if(len > 0){
                load();
            }else{
                $loadHtml.hide();
                progress("100%");
                if(callback){
                    callback();
                }
            }
            return {
                pics: pics,
                load: load,
                progress: progress
            };
        },
        Dialog:function(cfg){

            if(cfg == 'CLOSE'){

                var panel = $('.ui_panel');

                if(panel){

                    (panel.parent()).remove();
                }

            }else{
                cfg.LabelOk = cfg.LabelOk?cfg.LabelOk:'确定';

                cfg.LabelCancel = cfg.LabelCancel?cfg.LabelCancel:'取消';

                cfg.title = cfg.title?cfg.title:(cfg.type=='Confirm'?'确认':'提示');

                var panel,btnstr;

                if(cfg.type == 'Alert' || cfg.type == 'Confirm'){

                    btnstr = (cfg.type == 'Alert')?'<span id="ui_btn_ok" >'+cfg.LabelOk+'</span>':'<span id="ui_btn_ok">'+cfg.LabelOk+'</span><span id="ui_btn_cancel">'+cfg.LabelCancel+'</span>';

                    panel = $('<div id="dialog_div">\
                                    <div class="ui_panel"></div>\
                                    <div class="popup br-5">\
                                        <div class="head f14 white t-overflow">'+cfg.title+'</div>\
                                    <div id="dialog__content" class="body"> '+cfg.content+'</div>\
                                    <div class="foot popup_btn">' + btnstr + '</div>\
                                </div>');


                }else if(cfg.type == 'Dialog'){
                    if(cfg.isAppend&&$("#dialog__content").length){  //追加内容
                        $("#dialog__content").append("<br/>"+cfg.content);
                    }else{
                        panel = $('<div id="dialog_div">\
                                    <div class="ui_panel"></div>\
                                    <div class="popup br-5">\
                                        <div class="head f14 white t-overflow">'+cfg.title+'</div>\
                                    <div id="dialog__content" class="body"> '+cfg.content+'</div>\
                                </div>');
                    }
                    if(cfg.times){
                        setTimeout(function(){
                            $("#dialog_div").hide();
                        },cfg.times);
                    }
                }

                if(panel){
                    panel.css({
                        'position':'fixed',
                        'left':'0',
                        'right':'0',
                        'top':'0',
                        'bottom':'0',
                        'z-index':'99999'
                    });
                    if($("#dialog_div").length){
                        $("#dialog_div").remove();
                    }
                    panel.appendTo($('body'));
                    (function(panel,cfg){

                        setTimeout(function(){

                            if(cfg.CallBackOk){
                                $(panel.find('#ui_btn_ok')).bind('click',cfg.CallBackOk);
                            }
                            if(cfg.CallBackCancel){
                                $(panel.find('#ui_btn_cancel')).bind('click',cfg.CallBackCancel);
                            }else{
                                $(panel.find('#ui_btn_cancel')).bind('click',function(){UI.Dialog('CLOSE');});
                            }
                        },16);

                    })(panel,cfg);
                }

                /*
                 var dialogdom =$('[name=jitdialog]');
                 dialogdom.css({
                 'left':(Jit.winSize.width-dialogdom.width())/2,
                 'top':(Jit.winSize.height-dialogdom.height())/2,
                 });
                 */
            }
        },
        Alert:function(msg,callback){
            this.Dialog({
                type : "Alert",
                content : msg,
                CallBackOk : function() {
                    if(callback){
                        callback();
                    }
                    $.ui.Dialog("CLOSE");
                }
            })
        },
        Confirm:function(msg,callback){
            this.Dialog({
                type : "Confirm",
                content : msg,
                CallBackOk : function() {
                    if(callback){
                        callback();
                    }
                    $.ui.Dialog("CLOSE");
                }
            })
        },
        Masklayer:{

            show:function(){

                if($('#masklayer').length<=0){

                    var mask = $('<div id="masklayer" style="position:fixed;background-color:#ECECEC;width:100%;height:100%;line-height:100%;z-index:9999;top:0;left:0;text-align:center"></div>');

                    mask.appendTo('body');
                }

                $('#masklayer').css({'opacity':'0.6'}).show();
            },
            hide:function(){

                $('#masklayer').hide();
            }
        },
        Loading:function(display,msg){

            if(display||arguments.length==0){

                msg = msg || '正在加载...';
                if($(".ui_loading").length){
                    $(".ui_loading").remove();
                }
                var _html = '<class="ui_loading">'
                            + 	'<div class="ui_loading_inner">'
                            + 		'<i class="ui_loading_icon"></i>'
                            + 		'<span>'+ msg +'</span>'
                            +		'</div>'
                            +	'</div>'

                $('body').append(_html);

            }else{
                $('.ui_loading').remove();
            }
        },
        AjaxTips:{
            //显示ajax加载数据的时候   出现加载图标
            Loading:function(flag){

                if(flag||arguments.length==0){
                    //显示loading

                    UI.Loading(true);

                }else{
                    //隐藏loading

                    UI.Loading(false);
                }
            },
            //加载数据
            Tips:function(options){
                var left="50%",
                    top="50%";
                if(options.left){
                    left=options.left;
                }
                if(options.top){
                    top=options.top;
                }
                if(options.show){//显示tips
                    if($("#ajax__tips").length>0){
                        $("#ajax__tips").remove();
                    }
                    var style="position:fixed;top:"+top+";  left:"+left+";  width:100px;  height:100px;margin-top:-50px;margin-left:-50px;text-align: center;line-height100px;";
                    var $div=$("<div id='ajax__tips' style='"+style+"'>"+(options.tips?options.tips:"暂无数据")+"</div>");
                    $("body").append($div);

                }else{  //隐藏tips
                    $("#ajax__tips").hide();
                }
            }
        }

    };
    $.ui = UI;
})(jQuery);